package cn.jobstart.common.spider;

import cn.jobstart.common.SkMap;
import cn.jobstart.common.StringUtil;
import com.alibaba.fastjson.JSONObject;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.logging.LogEntry;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sunke
 * @version 1.0
 * @Description 猎聘
 * @date 2023-12-06 10:54
 */
@Component
public class LiePinUtil extends TokenUtil {


    private final String loginUrl = "https://lpt.liepin.com/user/login";
    private final String username = "LPT76632SZNA";
    private final String password = "blue@123";

    private final String FSCP_TRACE_ID = "X-Fscp-Trace-Id";
    private final String XSRF_TOKEN = "X-XSRF-TOKEN";
    private final String FSCP_STD_INFO = "X-Fscp-Std-Info";
    private final String LIE_PIN_TOKEN = "liepin_token";


    public void removeToken(){

        try{

            getRedisUtil().del(LIE_PIN_TOKEN);
        }catch (Exception e){

        }


    }

    public void initAuthorization() {

        do {
            try {
                LiePinToken liePinToken = getToken();
                if (StringUtil.isNotObjEmpty(liePinToken)) {
                    return;
                }
                createAuthorization();

            } catch (Exception e) {
                e.printStackTrace();
            }finally {

            }

        } while (true);
    }


    public LiePinToken getToken() {
        try {
            return JSONObject.parseObject((String) getRedisUtil().get(LIE_PIN_TOKEN), LiePinToken.class);
        } catch (Exception e) {
            return null;
        }

    }

    public void setToken(LiePinToken liePinToken) {
        if (StringUtil.isNullOrEmpty(liePinToken)) {
            return;
        }
        getRedisUtil().set(LIE_PIN_TOKEN, JSONObject.toJSONString(liePinToken));


    }


    public void createAuthorization() throws Exception {

        System.getProperties().setProperty("webdriver.chrome.driver", getFileConfig().getChromeDriverPath());
        System.setProperty("webdriver.chrome.whitelistedIps", "");

        ChromeOptions options = new ChromeOptions();
        options.addArguments("--allowed-ips", "--disable-web-security");
        options.setCapability("goog:loggingPrefs", SkMap.getInstance().addObjToMap("performance", "ALL"));


        WebDriver webDriver = new ChromeDriver(options);
        webDriver.manage().window().maximize();
        // 添加一个隐式等待，用于等待页面元素加载完成
        webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        webDriver.get(loginUrl);
        sleep(2000);

        WebElement webElement = webDriver.findElement(By.xpath("//*[@id=\"main-container\"]/div/div/div[2]/div/div/div/ul/li[2]"));
        webElement.click();
        sleep(1000);

        webDriver.findElement(By.xpath("//*[@id=\"main-container\"]/div/div/div[2]/div/div/div/div/div[1]/div[1]/input")).sendKeys(username);
        webDriver.findElement(By.xpath("//*[@id=\"main-container\"]/div/div/div[2]/div/div/div/div/div[1]/div[2]/input")).sendKeys(password);
        webDriver.findElement(By.xpath("//*[@id=\"main-container\"]/div/div/div[2]/div/div/div/div/div[2]/button")).click();


        webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        sleep(10000);


/*

        WebElement dragButton= webDriver.findElement(By.xpath("//*[@id=\"tcaptcha_drag_thumb\"]"));

        Actions dragAction= new Actions(webDriver);
        dragAction.clickAndHold(dragButton).perform();
        for(int i=0;i<1000;i=i+2){
            System.out.println(i);
            dragAction.moveToElement(dragButton,i,0);
            dragAction.perform();

        }
*/




     //   webDriver.get("https://lpt.liepin.com/cvsearch/showcondition");
       // webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


/*        webDriver.findElement(By.xpath("//*[@id=\"search-keywords-edu\"]/div/div[2]/div/input")).sendKeys("java");
        sleep(1000);
        webDriver.findElement(By.xpath("//*[@id=\"search-keywords-edu\"]/button")).click();
        sleep(1000);
        webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);*/

        Set<Cookie> cookies = webDriver.manage().getCookies();

        List<LogEntry> logList = webDriver.manage().logs().get("performance").getAll();

        logList = logList.stream().sorted(Comparator.comparing(LogEntry::getTimestamp).reversed()).collect(Collectors.toList());

        for (LogEntry log : logList) {
            try {
                JSONObject jsonObject = JSONObject.parseObject(log.getMessage());
                JSONObject msgJson = jsonObject.getJSONObject("message");
                JSONObject paramsJson = msgJson.getJSONObject("params");
                JSONObject headerJson = paramsJson.getJSONObject("request").getJSONObject("headers");

                if (headerJson.containsKey(FSCP_TRACE_ID) && headerJson.containsKey(XSRF_TOKEN) && headerJson.containsKey(FSCP_STD_INFO)) {
                    LiePinToken token = new LiePinToken();
                    for (String key : headerJson.keySet()) {
                        if (key.equalsIgnoreCase(FSCP_TRACE_ID)) {
                            token.setTraceId(headerJson.getString(FSCP_TRACE_ID));
                        } else if (key.equalsIgnoreCase(XSRF_TOKEN)) {
                            token.setXsrfToken(headerJson.getString(XSRF_TOKEN));
                        } else if (key.equalsIgnoreCase(FSCP_STD_INFO)) {
                            token.setStdInfo(headerJson.getString(FSCP_STD_INFO));
                        }

                        token.addMap(key, headerJson.getString(key));

                    }
                    token.setCookie(cookies.stream().map(cookie -> cookie.getName() + "=" + cookie.getValue()).collect(Collectors.joining(";")));
                    token.addMap("Cookie", token.getCookie());

                    setToken(token);
                    break;

                }

            } catch (Exception e) {

            }

        }

        webDriver.quit();

    }


}
